package Sort;

public class sort7 {
    //归并排序
    public static void main(String[] args) {
        int[] arr = {10, 5, 21, 6, 7, 2, 9, 11, 3, 1};
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        mergeSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    private static void mergeSort(int[] arr) {
//        mergeSortFunc(arr, 0, arr.length - 1);
        mergrSortNor(arr);

    }

    //递归的方式
    private static void mergeSortFunc(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = (left + right) / 2;
        //分解
        mergeSortFunc(arr, left, mid);
        mergeSortFunc(arr, mid + 1, right);
        //合并
        merge(arr, left, right, mid);
    }
    //合并两个有序数组(借助一个临时数组)
    private static void merge(int[] arr, int left, int right, int mid) {
        int s1 = left;
        int s2 = mid+1;
        int[] tmpArr = new int[right - left + 1];
        int k = 0;

        while (s1 <= mid && s2 <= right) {
            if (arr[s1] <= arr[s2]) {
                tmpArr[k++] = arr[s1++];
            }
            if (arr[s2] <= arr[s1]) {
                tmpArr[k++] = arr[s2++];
            }
        }

        while (s1 <= mid) {
            tmpArr[k++] = arr[s1++];
        }
        while (s2 <= right) {
            tmpArr[k++] = arr[s2++];
        }

        for (int i = 0; i < tmpArr.length; i++) {
            arr[i+left] = tmpArr[i];
        }
    }

    //非递归方法
    public static void mergrSortNor(int[] arr){
        int gap = 1;
        while(gap<arr.length){

            for (int i = 0; i < arr.length; i+=2*gap) {
                int left = i;
                int mid = left+gap-1;
                int right = mid + gap;
                if(mid>= arr.length){
                    mid = arr.length-1;
                }
                if(right>= arr.length){
                    right = arr.length-1;
                }
                merge(arr,left,right,mid);
            }
            //这里必须*=2,想一下上面的递归方法，类似于二叉树
            gap*=2;
        }
    }
}
